﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Newtonsoft.Json;
using System.IO;
using Path = System.IO.Path;
using ScriptBox;
using System.Diagnostics;
using System.Windows.Threading;
using System.Collections.ObjectModel;

namespace ScriptBox
{
    public partial class ProjectManagementDialog : Window
    {
        private AI_ScriptProject _scriptProject;
        private string _projectPath;
        private string _editorpath;

        public AI_ScriptProject CurrentProject => _scriptProject;

        public ProjectManagementDialog(string editorpath, string projectPath)
        {
            InitializeComponent();
            _editorpath = editorpath;
            _projectPath = projectPath;
            LoadProject();
        }

        private void LoadProject()
        {
            try
            {
                var json = File.ReadAllText(_projectPath);
                _scriptProject = JsonConvert.DeserializeObject<AI_ScriptProject>(json);
                ProcessPaths(true);
                PopulateProjectTree();
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show($"工程加载失败：{ex.Message}");
                Close();
            }
        }

        private void ProcessPaths(bool isLoading)
        {
            var baseDir = Path.GetDirectoryName(_projectPath);
            if (string.IsNullOrEmpty(baseDir)) return;

            if (isLoading)
            {
                _scriptProject.WorkDir = Path.GetFullPath(Path.Combine(baseDir, _scriptProject.WorkDir));
            }
            else
            {
                _scriptProject.WorkDir = Path.GetRelativePath(baseDir, _scriptProject.WorkDir);
            }
        }

        private void PopulateProjectTree()
        {
            ProjectTree.Items.Clear();
            if (_scriptProject != null)
            {
                ProjectTree.Items.Add(_scriptProject);
            }
        }

        private void BtnSave_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                ProcessPaths(false);
                var json = JsonConvert.SerializeObject(_scriptProject, Formatting.Indented);
                File.WriteAllText(_projectPath, json);
                DialogResult = true;
                Close();
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show($"保存失败：{ex.Message}");
            }
        }

        private void BtnCancel_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = false;
            Close();
        }

        private void BtnEdit_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = false;
            Process.Start(_editorpath, $"\"{_projectPath}\"");
            Close();
        }

        private void AddItem_Click(object sender, RoutedEventArgs e)
        {
            var selected = ProjectTree.SelectedItem;

            if (selected is AI_ScriptProject project)
            {
                var newGroup = new AI_ButtonGroup { GroupName = "New Group" };
                project.ButtonGroups.Add(newGroup);
                ExpandAndSelect(newGroup);
            }
            else if (selected is AI_ButtonGroup group)
            {
                var newButton = new AI_ScriptButton { Title = "New Button", ScriptType = "cmd", ScriptContent = "echo hello echo" };
                group.Buttons.Add(newButton);
                ExpandAndSelect(newButton);
            }
        }

        private void ExpandAndSelect(object item)
        {
            // 延迟执行确保UI更新完成
            Dispatcher.BeginInvoke(() =>
            {
                var container = FindTreeViewItem(ProjectTree, item);
                if (container != null)
                {
                    container.IsExpanded = true;
                    container.IsSelected = true;
                    container.BringIntoView();
                }
            }, DispatcherPriority.ContextIdle);
        }

        private TreeViewItem FindTreeViewItem(ItemsControl parent, object item)
        {
            if (parent == null || item == null) return null;

            if (parent.ItemContainerGenerator.ContainerFromItem(item) is TreeViewItem container)
                return container;

            foreach (var childItem in parent.Items)
            {
                var childContainer = parent.ItemContainerGenerator.ContainerFromItem(childItem) as TreeViewItem;
                var found = FindTreeViewItem(childContainer, item);
                if (found != null) return found;
            }

            return null;
        }

        private void DeleteItem_Click(object sender, RoutedEventArgs e)
        {
            var selected = ProjectTree.SelectedItem;
            if (selected == null) return;

            if (selected is AI_ScriptProject)
            {
                System.Windows.MessageBox.Show("不能删除根项目");
                return;
            }

            // 记录父节点和兄弟项（用于后续选中相邻项）
            object parentCollection = null;
            object siblingToSelect = null;
            if (selected is AI_ButtonGroup group)
            {
                parentCollection = _scriptProject.ButtonGroups;
                int index = _scriptProject.ButtonGroups.IndexOf(group);
                _scriptProject.ButtonGroups.Remove(group);

                // 确定要选中的相邻项（优先选前一项，如果存在的话）
                siblingToSelect = index > 0
                    ? _scriptProject.ButtonGroups[index - 1]
                    : _scriptProject.ButtonGroups.FirstOrDefault();
            }
            else if (selected is AI_ScriptButton button)
            {
                foreach (var bg in _scriptProject.ButtonGroups)
                {
                    if(bg.Buttons.Contains(button))
                    {
                        parentCollection = bg.Buttons;
                        int index = bg.Buttons.IndexOf(button);
                        bg.Buttons.Remove(button);

                        // 确定要选中的相邻项
                        siblingToSelect = index > 0
                            ? bg.Buttons[index - 1]
                            : bg.Buttons.FirstOrDefault();
                        break;
                    }
                }
            }
            // 自动选中相邻项并保持展开状态
           Dispatcher.BeginInvoke(() =>
            {
                if (siblingToSelect != null)
                {
                    var container = FindTreeViewItem(ProjectTree, siblingToSelect);
                    container?.BringIntoView();
                    container?.Focus();
                }
                else if (parentCollection != null)
                {
                    // 使用改进后的switch表达式
                    object parentItem = null;
                    if (parentCollection is ObservableCollection<AI_ButtonGroup>)
                    {
                        parentItem = _scriptProject;
                    }
                    else if (parentCollection is ObservableCollection<AI_ScriptButton> buttons)
                    {
                        parentItem = _scriptProject.ButtonGroups.FirstOrDefault(bg => bg.Buttons == buttons);
                    }

                    if (parentItem != null)
                    {
                        var parentContainer = FindTreeViewItem(ProjectTree, parentItem);
                        parentContainer?.BringIntoView();
                        parentContainer?.Focus();
                    }
                }
            }, DispatcherPriority.ContextIdle);
        }

        private void ProjectTree_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            var selectedItem = ((TreeView)sender).SelectedItem;

            // 处理TreeViewItem嵌套的情况
            if (selectedItem is TreeViewItem treeViewItem)
            {
                ShowPropertyEditor(treeViewItem.Header);
            }
            else
            {
                ShowPropertyEditor(selectedItem);
            }
        }

        private void ShowPropertyEditor(object item)
        {
            if (item is AI_ScriptProject project)
            {
                PropertyEditor.Content = new ProjectEditor { DataContext = project };
            }
            else if (item is AI_ButtonGroup group)
            {
                PropertyEditor.Content = new GroupEditor { DataContext = group };
            }
            else if (item is AI_ScriptButton button)
            {
                PropertyEditor.Content = new ButtonEditor { DataContext = button };
            }
        }

        public static string GetRelativePath(string fromPath, string toPath)
        {
            // 处理路径分隔符统一化
            fromPath = Path.GetFullPath(fromPath).Replace(Path.DirectorySeparatorChar, '/');
            toPath = Path.GetFullPath(toPath).Replace(Path.DirectorySeparatorChar, '/');

            var fromUri = new Uri(fromPath);
            var toUri = new Uri(toPath);

            // 如果是文件路径，需要确保最后带斜杠
            if (!fromPath.EndsWith("/") && !fromPath.EndsWith("\\"))
            {
                fromUri = new Uri(fromPath + "/");
            }

            Uri relativeUri = fromUri.MakeRelativeUri(toUri);
            string relativePath = Uri.UnescapeDataString(relativeUri.ToString())
                                   .Replace('/', Path.DirectorySeparatorChar);

            // 处理相同路径的情况
            if (string.IsNullOrEmpty(relativePath))
            {
                return "." + Path.DirectorySeparatorChar;
            }

            return relativePath;
        }

        private void PathConvert_Click(object sender, RoutedEventArgs e)
        {
            var selected = ProjectTree.SelectedItem;
            if (selected == null) return;

            if (selected is AI_ScriptButton button)
            {
                string projectpath = Path.GetDirectoryName(_projectPath);
                string workdir = _scriptProject.WorkDir;
                //Image Path
                var img_path = button.ImgPath;
                if (File.Exists(img_path))
                {
                    img_path = GetRelativePath(projectpath, img_path);
                    button.ImgPath = img_path;
                }

                //ScriptContent Path 
                if (button.ScriptType == "file")
                {
                    var contentpath = button.ScriptContent;
                    if (File.Exists(contentpath))
                    {
                        contentpath = GetRelativePath(workdir, contentpath);
                        button.ScriptContent = contentpath;
                    }
                } else if (button.ScriptType == "dir")
                {
                    var contentpath = button.ScriptContent;
                    if (Directory.Exists(contentpath))
                    {
                        contentpath = GetRelativePath(workdir, contentpath);
                        button.ScriptContent = contentpath;
                    }
                }
            }
        }

        private object _draggedItem;
        private Point _dragStartPoint;

        private void TreeView_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            _dragStartPoint = e.GetPosition(null);
            _draggedItem = ((DependencyObject)e.OriginalSource).GetParentOfType<TreeViewItem>()?.Header;
        }

        private void TreeView_PreviewMouseMove(object sender, MouseEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed && _draggedItem != null)
            {
                Point position = e.GetPosition(null);
                if (Math.Abs(position.X - _dragStartPoint.X) > SystemParameters.MinimumHorizontalDragDistance ||
                    Math.Abs(position.Y - _dragStartPoint.Y) > SystemParameters.MinimumVerticalDragDistance)
                {
                    DragDrop.DoDragDrop(ProjectTree, _draggedItem, DragDropEffects.Move);
                    _draggedItem = null;
                }
            }
        }

        private void TreeView_DragEnter(object sender, DragEventArgs e)
        {
            if (!e.Data.GetDataPresent(typeof(AI_ButtonGroup)) && !e.Data.GetDataPresent(typeof(AI_ScriptButton)))
            {
                e.Effects = DragDropEffects.None;
            }
            e.Handled = true;
        }

        private void TreeView_Drop(object sender, DragEventArgs e)
        {
            if (_draggedItem == null) return;

            // 获取目标位置
            var targetItem = ((DependencyObject)e.OriginalSource).GetParentOfType<TreeViewItem>()?.Header;
            var dropPosition = e.GetPosition((UIElement)sender);

            // 处理不同类型的拖拽
            switch (_draggedItem)
            {
                case AI_ButtonGroup draggedGroup:
                    HandleGroupDrag(draggedGroup, targetItem, dropPosition);
                    break;

                case AI_ScriptButton draggedButton:
                    HandleButtonDrag(draggedButton, targetItem, dropPosition);
                    break;
            }

            e.Handled = true;
        }

        private void HandleGroupDrag(AI_ButtonGroup draggedGroup, object targetItem, Point dropPosition)
        {
            // 从原位置移除
            _scriptProject.ButtonGroups.Remove(draggedGroup);

            // 确定插入位置
            if (targetItem is AI_ScriptProject)
            {
                // 拖到根节点
                _scriptProject.ButtonGroups.Add(draggedGroup);
            }
            else if (targetItem is AI_ButtonGroup targetGroup)
            {
                // 拖到其他组上方
                int index = _scriptProject.ButtonGroups.IndexOf(targetGroup);
                _scriptProject.ButtonGroups.Insert(index, draggedGroup);
            }
        }

        private void HandleButtonDrag(AI_ScriptButton draggedButton, object targetItem, Point dropPosition)
        {
            // 先从原组移除
            AI_ButtonGroup sourceGroup = null;
            foreach (var group in _scriptProject.ButtonGroups)
            {
                if (group.Buttons.Contains(draggedButton))
                {
                    sourceGroup = group;
                    group.Buttons.Remove(draggedButton);
                    break;
                }
            }

            if (sourceGroup == null) return;

            // 确定目标位置
            if (targetItem is AI_ButtonGroup targetGroup)
            {
                // 拖到组内
                targetGroup.Buttons.Add(draggedButton);
            }
            else if (targetItem is AI_ScriptButton targetButton)
            {
                // 拖到具体按钮位置
                foreach (var group in _scriptProject.ButtonGroups)
                {
                    if (group.Buttons.Contains(targetButton))
                    {
                        int index = group.Buttons.IndexOf(targetButton);
                        group.Buttons.Insert(index, draggedButton);
                        break;
                    }
                }
            }
            if (targetItem == null)
            {
                sourceGroup.Buttons.Add(draggedButton);
            }
        }
    }

    public static class VisualTreeHelperExtensions
    {
        public static T GetParentOfType<T>(this DependencyObject child) where T : DependencyObject
        {
            DependencyObject parent = VisualTreeHelper.GetParent(child);
            while (parent != null && !(parent is T))
            {
                parent = VisualTreeHelper.GetParent(parent);
            }
            return parent as T;
        }
    }
}
